package com.cenwangkeji.resident.presenter.activity;

import com.cenwangkeji.resident.model.Constant;
import com.cenwangkeji.resident.model.OkHttpUtils;
import com.cenwangkeji.resident.model.bean.ImgBean;
import com.cenwangkeji.resident.model.bean.SuccessBean;
import com.cenwangkeji.resident.model.bean.User;
import com.google.gson.Gson;
import com.lws.basic.persenter.ObserverOnNext;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.RxUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.transform.OutputKeys;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

/**
 * @松 on 2019/11/8 11:25
 * //添加问题逻辑
 */
public class AddQuestionPresenter {
    private I mI;

    public AddQuestionPresenter(I i) {
        mI = i;
    }

    public void add(final String title, final String content, final List<String> images){
        Observable.create(new ObservableOnSubscribe<SuccessBean>() {
            @Override
            public void subscribe(ObservableEmitter<SuccessBean> emitter) throws Exception {
                Map<Object,Object> map = new HashMap<>();
                Gson gson = new Gson();
                if (images!= null&& images.size() >0) {
                    for (int i=0;i<images.size();i++) {
                        String json = OkHttpUtils.uploadImage(Constant.image_url, new File(images.get(i)));
                        ImgBean bean = gson.fromJson(json, ImgBean.class);
                        map.put("picid"+(i+1), bean.getFileUrl().get(0));
                    }
                }
                map.put("wtbt", title);
                map.put("wdnr",content);
                map.put( Constant.token, User.getToken());
                map.put( "mark",3);
                map.put("jmid", User.getUserId());
                map.put("wdType",1);
                map.put("ysid", User.getDoctorId());
                JSONObject jsonObject = new JSONObject(map);
                MyLogger.i(jsonObject.toString());
                String json = OkHttpUtils.post(jsonObject.toString(), Constant.question_add);
                MyLogger.i(json);
                SuccessBean successBean  = gson.fromJson(json, SuccessBean.class);
                emitter.onNext(successBean);

            }
        }).compose(RxUtils.<SuccessBean>io_main())
                .subscribe(new ObserverOnNext<SuccessBean>() {
                    @Override
                    public void onNext(SuccessBean bean) {
                       if (mI!= null){
                          mI.onAddSuccess(bean);
                       }
                    }
                });

    }

    public interface I{
        void onAddSuccess(SuccessBean bean);
    }
}
